package com.simple.microservices.commons.handlers;

import com.simple.microservices.commons.exceptions.BusinessException;
import com.simple.microservices.commons.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.google.common.base.Throwables;
import java.util.HashMap;
import java.util.Map;

/**
 * 参数 异常统一处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * service 手动抛出异常
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public Response handleValidationExceptions(BusinessException ex) {
        //单个参数校验
        String exMessage = ex.getMessage();
        log.error("已知异常-KnowException = {}",exMessage);
        Map<String,Object> map =  getMsg(exMessage);
        String msg = "";
        if(map.get("flag").equals(true)){
            msg = map.get("msg").toString();
        }else{
           msg = exMessage;

        }

        return Response.errorMsg(msg);
    }


    /**
     * 参数异常校验 统一返回200 使用内部code 处理
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleValidationExceptions(MethodArgumentNotValidException ex) {

        //单个参数校验
        String exMessage = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数异常校验 = {}",exMessage);
        Map<String,Object> map =  getMsg(exMessage);
        String msg = "";
        if(map.get("flag").equals(true)){
            msg = map.get("msg").toString();
        }else{

                msg = exMessage;
        }

        return Response.errorMsg(msg);

//多参数校验
//        JSONObject errors = new JSONObject();
//        ex.getBindingResult().getAllErrors().forEach((error) -> {
//            String fieldName = ((FieldError) error).getField();
//            String errorMessage = error.getDefaultMessage();
//            errors.put(fieldName, errorMessage);
//        });
//
//        log.error("参数异常 = {}",errors);
//        return Response.errorMsg(errors.toJSONString());
    }



    /**
     * 缺少请求体异常处理器
     *
     * @param e 缺少请求体异常
     * @return ResponseResult
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        log.error("缺少参数请求体");
        String msg = "缺少请求参数";
        return Response.errorMsg(msg);
    }
    /**
     * 处理其他异常
     *
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Response exceptionHandler( Exception e) {
        e.printStackTrace();
        //单个参数校验
        log.error("处理其他异常 = {}",Throwables.getStackTraceAsString(e));
        Map<String,Object> map =  getMsg("参数异常");
        String msg = "";
        if(map.get("flag").equals(true)){
            msg = map.get("msg").toString();
        }else{
            if (StringUtils.isEmpty(msg)){
                msg = "参数异常";
            }
        }
        return Response.errorMsg(msg);
    }

    /**
     * 获取国际化Msg
     * @param exMessage
     * @return
     */
    public Map<String,Object> getMsg(String exMessage){
        Map<String,Object> map = new HashMap<>();
        Boolean flag = false;
        String msg = exMessage;
        map.put("flag",flag);
        map.put("msg",msg);
        return map;
    }
}